#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QStandardItem>
#include <QMap>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)

    , model(new QStandardItemModel(this))
{
    ui->setupUi(this);
    model->setHorizontalHeaderLabels(QStringList(QStringLiteral("资源")));

}

MainWindow::~MainWindow()
{
    delete ui;
}



void
MainWindow::generateTree(
    int argc,
    char** argv)
{
    auto nodes = HoffmanTreeByGoldfish::generateNodes(argc - 1, argv + 1);
    qDebug() << "--generated--";
    HoffmanTreeByGoldfish::reduce(nodes);

    model->invisibleRootItem()->appendRow( getRoot(nodes[0]));
    ui->treeView->setModel(model);
    ui->treeView->expandAll();
    ui->treeView->show();
}

QStandardItem*
MainWindow::getRoot(HoffmanTreeNode*root)
{
    if(root == nullptr)
    {
        qDebug("view cannot be built from null view");
        exit(1);
    }
    QHash<HoffmanTreeNode*, QStandardItem*> qmap;
    auto& map = qmap;

    QQueue<HoffmanTreeNode*> nodes;
    nodes.enqueue(root);
    qmap.insert(root, new QStandardItem());
    while(nodes.size() > 0)
    {
        HoffmanTreeNode* elem = nodes.dequeue();
        QStandardItem* item = map[elem];

        QList<QStandardItem*>childItems;
        HoffmanTreeNode *child = elem->getLeft();
        if(child)
        {

            QStandardItem* item = new QStandardItem();
            qmap.insert(child, item);
            item->setText(child->nodeNames());
            item->setToolTip(QString::asprintf("%d", child->nodeWeightSum()));
            childItems.append(qmap[child]);
            nodes.enqueue(child);
        }
        child = elem->getRight();
        if(child)
        {

            QStandardItem* item = new QStandardItem();
            qmap.insert(child, item);
            item->setText(child->nodeNames());
            item->setToolTip(QString::asprintf("%d", child->nodeWeightSum()));
            childItems.append(qmap[child]);
            nodes.enqueue(child);
        }
        item->appendRows(childItems);
    }
    return map[root];

}

